import {createSlice} from "@reduxjs/toolkit";
import {
    fetchAddConsume,
    fetchConsumePageData,
    fetchDeleteConsume,
    fetchLoadItemOptions,
    fetchUpdateConsume
} from "./async/consumeAsyncAction";

import {DefaultOptionType} from "rc-select/lib/Select";
import {compareObjectMergeProps} from "util/compare";
import LogFactory from "log/LogFactory";
import {Consume} from "type/Consume";
import System from "global/System";
import {StateBaseType} from "../StateBaseType";
import {ReduxStatus} from "enum/ReduxStatus";

const log = LogFactory.getLog("consumeReducer") ;
/**
 * 消费记录状态
 */
export type ConsumeState = StateBaseType<Consume> & {
    /**
     * 消费项目选项
     */
    itemOptions?: DefaultOptionType[] ;
    /**
     * 本月总消费
     */
    totalMoney: number ;
} ;

const initialState: ConsumeState = {
    data: [] ,
    pageSize: System.getInstance().getUserConfig().consumePageSize,
    current: 1,
    total: 0,
    totalMoney: 0,
    loading: false,
    status: ReduxStatus.INIT,
} ;

export const consumeReducer = createSlice({
    name: 'consume',
    initialState,
    reducers: {
        loadItemOptions: (state, action) => {
            // log.redux("加载消费项目选项: " , action.payload) ;
            state.itemOptions = action.payload ;
        }
    } ,
    extraReducers: (builder) => {
        builder.addCase(fetchConsumePageData.pending, (state) => {
            // log.redux("请求服务器获取消费记录数据加载中....") ;
            state.loading = true;
            state.status = ReduxStatus.PENDING
        });
        builder.addCase(fetchConsumePageData.fulfilled, (state, action) => {
            if (action.payload === null) {
                state.status = ReduxStatus.FAILED
                state.loading = false;
                return;
            }
            state.data = action.payload.data;
            state.pageSize = action.payload.pageSize;
            state.current = action.payload.currentPage;
            state.total = action.payload.total;
            state.totalMoney = action.payload.totalMoney
            state.loading = false;
            state.status = ReduxStatus.SUCCESS
        });
        builder.addCase(fetchAddConsume.fulfilled, (state, action) => {
            if (action.payload.success){
                // log.redux("添加消费记录成功,准备刷新数据");
                state.status = ReduxStatus.REFRESH
            }
        });
        builder.addCase(fetchUpdateConsume.fulfilled, (state, action) => {
            if (action.payload.result.success){
                // log.redux("修改消费记录成功,准备更新数据") ;
                let index = state.data.findIndex(item => item.id === action.payload.consume.id) ;
                if (index === -1){
                    log.warn("修改消费记录失败,没有找到对应的消费记录") ;
                    return ;
                }
                state.totalMoney = state.totalMoney - state.data[index].money + action.payload.consume.money ;
               // 此处因为state是代理对象,所以在比较合并的属性的时候就回自动更新,不需要后续处理
                compareObjectMergeProps(state.data[index],action.payload.consume) ;
                // 此处需要计算总额
                return ;
            }
            log.warn("修改消费记录失败");
        });
        builder.addCase(fetchLoadItemOptions.fulfilled, (state, action) => {
            if (action.payload == null){
                log.warn("加载消费项目选项失败数据");
                return ;
            }
            log.redux("加载消费项目选项数据: " , action.payload) ;
            state.itemOptions = action.payload.map(item => {
                return {label: item.item,value: item.item} ;
            }) ;
        });
        builder.addCase(fetchDeleteConsume.fulfilled, (state, action) => {
            if (action.payload.result){
                log.redux("删除消费记录成功,准备刷新数据") ;
                let index = state.data.findIndex(item => item.id === action.payload.id) ;
                if (index !== -1){
                    let tempMoney = state.data[index].money ;
                    state.total -= 1 ;
                    state.totalMoney -= tempMoney ;
                    state.data.splice(index,1) ;
                }
            }
        });
    }
});

export const {} = consumeReducer.actions ;
export default consumeReducer.reducer ;